import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/v1/users/login',
    method: 'post',
    data
  })
}

export function logout() {
  return request({
    url: '/v1/users/logout',
    method: 'post'
  })
}

export function fetchList(query) {
  return request({
    url: '/v1/users/user/',
    method: 'get',
    params: query
  })
}

export function createUser(data) {
  return request({
    url: '/v1/users/user/',
    method: 'post',
    data: {
      username: data.username,
      password: data.password,
      email: data.email || '',
      phone: data.phone || ''
    }
  })
}

export function updateUser(data) {
  const updateData = {
    username: data.username,
    email: data.email || '',
    phone: data.phone || '',
    uid: data.uid || ''
  }
  
  // 只在有新密码时才添加newPassword字段
  if (data.newPassword && data.newPassword.trim() !== '') {
    updateData.newPassword = data.newPassword
  }
  
  return request({
    url: `/v1/users/user/${data.id}/`,
    method: 'put',
    data: updateData
  })
}

export function deleteUser(id) {
  return request({
    url: `/v1/users/user/${id}/`,
    method: 'delete'
  })
}

export function checkToken(data) {
  return request({
    url: '/v1/users/check/token',
    method: 'get',
    data: {
      username: data.username,
      password: data.password
    }
  })
}

export function fetchTodoList() {
  return request({
    url: '/v1/users/todo/',
    method: 'get'
  })
}

export function createTodo(data) {
  return request({
    url: '/v1/users/todo/create_todo/',
    method: 'post',
    data
  })
}

export function deleteTodo(id) {
  return request({
    url: `/v1/users/todo/delete_todo/`,
    method: 'post',
    data: {
      id: id
    }
  })
}

export function getAvatar() {
  return request({
    url: '/v1/users/user/avatar/',
    method: 'get'
  })
}

export function uploadAvatar(userId, formData) {
  return request({
    url: `/v1/users/user/${userId}/upload-avatar/`,
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}
